package org.linlinjava.litemall.wx.web;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.redis.RedisCache;
import org.linlinjava.litemall.core.util.JsonUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallCategory;
import org.linlinjava.litemall.db.domain.LitemallCategorySupport;
import org.linlinjava.litemall.db.domain.LitemallGoods;
import org.linlinjava.litemall.db.domain.LitemallShop;
import org.linlinjava.litemall.db.service.LitemallCategoryService;
import org.linlinjava.litemall.db.service.LitemallCategorySupportService;
import org.linlinjava.litemall.db.service.LitemallGoodsService;
import org.linlinjava.litemall.db.service.LitemallShopService;
import org.linlinjava.litemall.db.util.HomeCacheManager;
import org.redisson.mapreduce.Collector;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageInfo;

import javax.validation.constraints.NotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 类目服务
 */
@RestController
@RequestMapping("/wx/catalogsupport")
@Validated
public class WxCatalogSupportController {
    private final Log logger = LogFactory.getLog(WxCatalogSupportController.class);

    @Autowired
    private LitemallCategoryService categoryService;
	@Autowired
	private LitemallGoodsService goodsService;
	@Autowired
	private LitemallCategorySupportService categorySupportService;
	@Autowired
	private LitemallShopService shopService;
	@Autowired
	private RedisCache redisCache;
	

    @GetMapping("/getfirstcategory")
    public Object getFirstCategory() {
        // 所有一级分类目录
        List<LitemallCategory> l1CatList = categoryService.queryL1();
        return ResponseUtil.ok(l1CatList);
    }

    @GetMapping("/getsecondcategory")
    public Object getSecondCategory(@NotNull Integer id) {
        // 所有二级分类目录
        List<LitemallCategory> currentSubCategory = categoryService.queryByPid(id);
        return ResponseUtil.ok(currentSubCategory);
    }

    /**
     * 分类详情
     *
     * @param id   分类类目ID。
     *             如果分类类目ID是空，则选择第一个分类类目。
     *             需要注意，这里分类类目是一级类目
     * @return 分类详情
     */
    @GetMapping("index")
    public Object index(Integer shopId) {
    	if(shopId == null) {
    		return ResponseUtil.badArgument();
    	}
        // 所有二级分类目录
        List<LitemallCategory> l2CatList = categoryService.queryL2(shopId);

        Map<String, Object> data = new HashMap<String, Object>();
        data.put("categoryList", l2CatList);
        data.put("currentSubCategory", l2CatList);
        LitemallCategory cy = new LitemallCategory();
        if(l2CatList.size()>0) {
        	//最后对应的商品
    		//查询列表数据
    		List<LitemallGoods> goodsList = goodsService.querySelective(l2CatList.get(0).getId());

    		/*
    		// 查询商品所属类目列表。
    		List<Integer> goodsCatIds = goodsService.getCatIds(null, null, null, null);
    		List<LitemallCategory> categoryList = null;
    		if (goodsCatIds.size() != 0) {
    			categoryList = categoryService.queryL2ByIds(goodsCatIds);
    		} else {
    			categoryList = new ArrayList<>(0);
    		}*/

    		PageInfo<LitemallGoods> pagedList = PageInfo.of(goodsList);

    		Map<String, Object> entity = new HashMap<>();
    		entity.put("list", goodsList);
    		entity.put("total", pagedList.getTotal());
    		entity.put("page", pagedList.getPageNum());
    		entity.put("limit", pagedList.getPageSize());
    		entity.put("pages", pagedList.getPages());
    		//entity.put("filterCategoryList", categoryList);
    		
    		data.put("list", goodsList);
    		
    		cy = l2CatList.get(0);
        	
        }
        data.put("currentCategory", cy);
        
        return ResponseUtil.ok(data);
    }
    
    @GetMapping("index2")
    public Object index2(Integer shopId) {
    	String cacheKey = "Catalog_info_"+shopId;
		if (redisCache.hasData(cacheKey)) {
			String json = redisCache.getCacheObject(cacheKey);
			return ResponseUtil.ok(JsonUtil.jsonToObject(json));
		}
    	Map<Object, Object> data = new HashMap<Object, Object>();
    	List<LitemallCategory> l2CatList = categoryService.queryL2(shopId);
    	if(l2CatList.size()>0) {
    		List<Integer> CategoryId = l2CatList.stream().map(LitemallCategory::getId).collect(Collectors.toList());
    		List<LitemallGoods> goodsList = goodsService.queryByCategory(CategoryId);
    		data.put("categoryList", l2CatList);
    		data.put("goodsList", goodsList);
    	}
    	redisCache.setCacheObject(cacheKey,JsonUtil.mapToJson(data));
    	return ResponseUtil.ok(data);
    }

    /**
     * 所有分类数据
     *
     * @return 所有分类数据
     */
    @GetMapping("all")
    public Object queryAll() {
        //优先从缓存中读取
        if (HomeCacheManager.hasData(HomeCacheManager.CATALOG)) {
            return ResponseUtil.ok(HomeCacheManager.getCacheData(HomeCacheManager.CATALOG));
        }


        // 所有一级分类目录
        List<LitemallCategory> l1CatList = categoryService.queryL1();

        //所有子分类列表
        Map<Integer, List<LitemallCategory>> allList = new HashMap<>();
        List<LitemallCategory> sub;
        for (LitemallCategory category : l1CatList) {
            sub = categoryService.queryByPid(category.getId());
            allList.put(category.getId(), sub);
        }

        // 当前一级分类目录
        LitemallCategory currentCategory = l1CatList.get(0);

        // 当前一级分类目录对应的二级分类目录
        List<LitemallCategory> currentSubCategory = null;
        if (null != currentCategory) {
            currentSubCategory = categoryService.queryByPid(currentCategory.getId());
        }

        Map<String, Object> data = new HashMap<String, Object>();
        data.put("categoryList", l1CatList);
        data.put("allList", allList);
        data.put("currentCategory", currentCategory);
        data.put("currentSubCategory", currentSubCategory);

        //缓存数据
        HomeCacheManager.loadData(HomeCacheManager.CATALOG, data);
        return ResponseUtil.ok(data);
    }

    /**
     * 当前分类栏目
     *
     * @param id 分类类目ID
     * @return 当前分类栏目
     */
    @GetMapping("current")
    public Object current(Integer id) {
    	if(id == null) {
    		return ResponseUtil.badArgumentValue();
    	}
    	LitemallCategorySupport categorySupport = categorySupportService.findById(id);
    	
    	if(categorySupport == null) {
    		return ResponseUtil.badArgumentValue();
    	}
    	List<LitemallShop> shopList = null;
    	if(categorySupport.getShopIds().length > 0) {
    		shopList = shopService.selectShoplist(categorySupport.getShopIds());
    	}
		
        Map<String, Object> entity = new HashMap<>();
        entity.put("currentShop", shopList);
        
        return ResponseUtil.ok(entity);
    }
}
